<!--
 * @Description: 订单管理
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2021-07-03 11:41:05
 * @LastEditTime: 2023-08-24 14:14:34
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-shop-order">
    <top-nav />
    <div class="page-main">
      <el-row class="page-search-form">
        <el-form
          @submit.native.prevent
          :inline="true"
          :model="searchForm"
          ref="listForm"
        >
          <el-form-item label="订单号" prop="order_no">
            <el-input
              v-model="searchForm.order_no"
              placeholder="请输入订单号"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="日期" prop="start_time">
            <el-date-picker
              @change="getTableDataList(1, 'list')"
              v-model="searchForm.start_time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              :picker-options="pickerOptions"
              :default-time="['00:00:00', '23:59:59']"
            >
            </el-date-picker>
          </el-form-item>
          
          <el-form-item
            label="订单类型"
            prop="type">
            <el-select
              @change="getTableDataList(1, 'list')"
              v-model="searchForm.type"
              placeholder="请选择"
            >
              <el-option
                v-for="item in serviceTypeList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="状态" prop="status">
            <el-select
              @change="getTableDataList(1, 'list')"
              v-model="searchForm.status"
              placeholder="请选择"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'list')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('list')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <el-row class="page-top-operate">
        
        <lb-button
          size="mini"
          plain
          type="primary"
          icon="el-icon-download"
          :loading="downloadLoading"
          @click="toExportExcel"
          v-hasPermi="`${$route.name}-export`"
        >
          {{ $t('action.export') }}</lb-button
        >
      </el-row>
      <!-- <div class="pb-lg">
        共<span class="c-warning">{{ total }}条</span
        >数据，订单金额共计：<span class="c-warning">{{ order_price }}元</span>
      </div> -->
      <el-table
        v-loading="loading"
        :data="tableData"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          fixed
        ></el-table-column>
		<el-table-column
		  prop="order_no"
		  label="订单号"
		  min-width="120"
		></el-table-column>
        <el-table-column
          prop="good_name"
          width="300"
          label="商品信息"
        >
          <template slot-scope="scope">
            <div
              class="pb-sm">
              <div class="flex-warp pt-md">
                <lb-image class="avatar radius-5" :src="scope.row.good_cover" />
                <div
                  class="flex-1 f-caption c-caption ml-md"
                  style="width: 210px"
                >
                  <div class="flex-between">
                    <div
                      class="f-paragraph c-title ellipsis" style="line-height: 1.2; margin-bottom: 4px"
                    >
                      {{ scope.row.good_name }}
                    </div>
                  </div>
                  <div>
                    <div class="c-warning">¥{{ scope.row.good_price }}</div>
                    <div>库存：{{ scope.row.good_total }}</div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
		
		<el-table-column
		  prop="username"
		  label="下单人"
		  min-width="300"
		>
			<template slot-scope="scope">
			  <div class="pb-sm">
			    <div class="flex-warp pt-md">
			      <lb-image class="avatar radius-5" :src="scope.row.user_avatar" />
			      <div class="flex-1 f-caption c-caption ml-md" style="width: 210px" >
			        <div class="f-paragraph c-title ellipsis" style="line-height: 1.2; margin-bottom: 4px" >
			          ID: {{ scope.row.user_id }}
			        </div>
					<div class="f-paragraph c-title ellipsis" style="line-height: 1.2; margin-bottom: 4px" >
					  昵称：{{ scope.row.user_nickname }}
					</div>
			      </div>
			    </div>
			  </div>
			</template>
		</el-table-column>
		
		<el-table-column
		  prop="username"
		  label="收货信息"
		  min-width="300"
		>
			<template slot-scope="scope">
			  <div class="pb-sm">
			    <div class="">
			      <div>
					  订单类型: 
					  <el-tag v-if="scope.row.type == 1">物流订单</el-tag>
					  <el-tag v-if="scope.row.type == 2" type="info">无需物流</el-tag>
				  </div>
			      <div v-if="scope.row.type == 1">
					  <div v-if="scope.row.express_id">
					  	快递单号：<span style="color: #f00; font-size: 16px;">{{scope.row.express_id}}</span>
					  </div>
					  <div>
						收件人：{{scope.row.username}}
					  </div>
					  <div>
					  	手机号：{{scope.row.mobile}}
					  </div>
					  <div>
					  	地址：{{scope.row.address}}
					  </div>
					  
			      </div>
				  <div v-if="scope.row.type == 2">
					  无
				  </div>
			    </div>
			  </div>
			</template>
		</el-table-column>
		
		<!-- '价格',
		'数量',
		'支付状态',
		'支付方式',
		'下单时间',
		'状态' -->
		<el-table-column
		  prop="pay_price"
		  label="价格"
		  min-width="140"
		>
			<template slot-scope="scope">
			    <div class="">
				  <div>单价：{{scope.row.price}}</div>
				  <div>数量：{{scope.row.number}}</div>
				  <div style="color: #f00;">总计：{{scope.row.pay_price}}</div>
			    </div>
			</template>
		</el-table-column>
		
		<el-table-column prop="pay_status" label="支付结果" min-width="140">
		  <template slot-scope="scope">
		    <div>
			  <el-tag v-if="scope.row.pay_status == 1">已支付</el-tag>
			  <el-tag v-if="scope.row.pay_status == 0" type="info">未支付</el-tag>
		    </div>
		    <div v-if="scope.row.pay_status == 1">
			  <div>
				支付时间：{{scope.row.pay_time}}
			  </div>
		    </div>
		  </template>
		</el-table-column>
		
		<el-table-column
		  prop="create_time"
		  label="下单时间"
		  min-width="120"
		></el-table-column>
		
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ statusType[scope.row.status] }}
          </template>
        </el-table-column>
		
		
        <el-table-column label="操作" min-width="160" fixed="right">
          <template slot-scope="scope">
            <div class="table-operate">
              
			  <lb-button v-if="scope.row.status == 0 || scope.row.status == -1 || scope.row.status == 3"
			    size="mini"
			    type="primary"
			    plain
			    @click="handleDelete(scope.row.id)"
			    v-hasPermi="`${$route.name}-view`"
			    >删除</lb-button
			  >
			  
			  <lb-button v-if="scope.row.status == 0"
			    size="mini"
			    type="primary"
			    plain
			    @click="handleCancel(scope.row.id)"
			    v-hasPermi="`${$route.name}-view`"
			    >取消</lb-button
			  >
			  
			  <!-- <lb-button v-if="scope.row.status == 1"
			    size="mini"
			    type="primary"
			    plain
			    @click="handleSend(scope.row.id, scope.row.type)"
			    v-hasPermi="`${$route.name}-view`"
			    >{{ scope.row.type == 1? '发货': '确认完成'}}</lb-button
			  > -->
			  
			  <template v-if="scope.row.status == 1">
				  <lb-button v-if="scope.row.type == 1 && !scope.row.express_id"
				    size="mini"
				    type="primary"
				    plain
				    @click="handleSend(scope.row.id, scope.row.type)"
				    v-hasPermi="`${$route.name}-view`"
				    >发货</lb-button
				  >
				  <lb-button v-if="scope.row.express_id"
				    size="mini"
				      type="primary"
				      plain
				      @click="handleExpress(scope.row.id, 'change', scope.row)"
				      v-hasPermi="`${$route.name}-view`"
				      >修改物流</lb-button
				    >
				  <lb-button v-if="scope.row.type == 2"
				    size="mini"
				    type="primary"
				    plain
				    @click="handleSend(scope.row.id, scope.row.type)"
				    v-hasPermi="`${$route.name}-view`"
				    >确认完成</lb-button
				  >
			  </template>
			  
			  <lb-button v-if="scope.row.status == 2"
			    size="mini"
			    type="primary"
			    plain
			    @click="handleExpress(scope.row.id, 'change', scope.row)"
			    v-hasPermi="`${$route.name}-view`"
			    >修改物流</lb-button
			  >
			  
			  <lb-button v-if="scope.row.status == 2"
			    size="mini"
			    type="primary"
			    plain
			    @click="handleComplete(scope.row.id)"
			    v-hasPermi="`${$route.name}-view`"
			    >确认收货</lb-button
			  >
			  
			  
			  
			  <!-- <lb-button
			    size="mini"
			    type="primary"
			    plain
			    @click="$router.push(`/shop/order/detail?id=${scope.row.id}`)"
			    v-hasPermi="`${$route.name}-view`"
			    >{{ $t('action.view') }}</lb-button
			  > -->
			  
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange($event, 'list')"
        @handleCurrentChange="handleCurrentChange($event, 'list')"
      >
      </lb-page>
	  
	  
	  <el-dialog title="提示" :visible.sync="expressPopup"  width="30%" :before-close="expressPopupClose">
		<div class="expressPopup">
			<el-form :model="expressForm" ref="expressForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="快递单号" prop="express_id" :rules="[
				  { required: true, message: '快递单号不能为空'}
				]">
					<el-input v-model="expressForm.express_id" ></el-input>
				</el-form-item>
				<el-form-item label="快递公司" prop="company" :rules="[
				  { required: true, message: '请选择快递公司'}
				]">
					<!-- <el-input v-model="expressForm.company" ></el-input> -->
					<el-select v-model="expressForm.company" filterable placeholder="请选择" @change="expressForm.companyName = companyOptions[companyOptions.findIndex((item) => item.value === $event)].label">
					    <el-option v-for="item in companyOptions" :key="item.value" :label="item.label" :value="item.value">
					    </el-option>
					</el-select>
				</el-form-item>
			</el-form>
		</div>
	    <span slot="footer" class="dialog-footer">
	      <el-button @click="expressPopup = false">取 消</el-button>
	      <el-button type="primary" @click="handleExpressSubmit()">确 定</el-button>
	    </span>
	  </el-dialog>

    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > (moment(moment(Date.now()).format('YYYY-MM-DD')).unix() + 24 * 3600 - 1) * 1000
        }
      },
      statusOptions: [
		  { label: '全部订单', value: 'all' },
		  // { label: '已退款', value: -3 }, { label: '退款中', value: -2 },
		  { label: '已取消', value: -1 }, { label: '待支付', value: 0 }, { label: '待发货', value: 1 }, { label: '待收货', value: 2 }, { label: '已完成', value: 3 }, 
	  ],
      serviceTypeList: [{ id: 0, title: '全部服务' }, { id: 1, title: '物流订单' }, { id: 2, title: '非物流订单' }],

      payType: {
        1: '微信支付',
        2: '余额支付',
        3: '支付宝支付'
      },
      statusType: {
  //       '-3': '已退款',
		// '-2': '退款中',
		'-1': '已取消',
		0: '待支付',
        1: '待发货',
        2: '待收货',
        3: '已完成',
      },
 
      
      loading: false,
      searchForm: {
       page: 1,
       limit: 10,
       // goods_name: '',
       order_no: '',
       // mobile: '',
       start_time: '',
       end_time: '',
       type: 0,
       status: 'all'
      },
      tableData: [],
      total: 0,
      order_price: 0,
      downloadLoading: false,
      lockTap: false,
	  
	  
	  expressPopup: false,
	  expressForm: {
		  express_id: null,
		  type: null,		// send 发货   change 修改物流
		  orderId: null,
		  company: null,
		  companyName: null,
	  },
	  
	  companyOptions: [
		  {label: '圆通速递', value: 'yuantong'},
		  {label: '申通快递', value: 'shentong'},
		  {label: '极兔速递', value: 'jtexpress'},
		  {label: '中通快递', value: 'zhongtong'},
		  {label: '韵达快递', value: 'yunda'},
		  {label: '邮政快递包裹', value: 'youzhengguonei'},
		  {label: '顺丰速运', value: 'shunfeng'},
		  {label: '京东物流', value: 'jd'},
		  {label: 'EMS', value: 'ems'},
		  {label: '菜鸟速递', value: 'danniao'},
		  {label: '德邦物流', value: 'debangwuliu'},
		  {label: '安能快运', value: 'annengwuliu'}
	  ]
	  
    }
  },
  async activated () {
    await this.getBaseInfo()
    this.getTableDataList(1, 'list')
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    async getBaseInfo () {
      let { code, data } = await this.$api.agent.adminSelect()
      if (code !== 200) return
      // this.base_agent = data
    },
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList('')
    },
    /**
     * @method 列表
     */
    getTableDataList (flag) {
      if (flag) this.searchForm.page = 1
      this.loading = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm))
      // if (key === 'list') {
        this.tableData = []
        let { start_time: time } = searchForm
        if (time && time.length > 0) {
          searchForm.start_time = time[0] / 1000
          searchForm.end_time = time[1] / 1000
        } else {
          searchForm.start_time = ''
          searchForm.end_time = ''
        }
      // }
      // let methodArr = {
      //   list: 'orderGoodList',
      //   transfer: 'orderChangeCoachList'
      // }
      let methodModel = 'orderGoodList'
      this.$api.shop[methodModel](searchForm).then(res => {
        this.loading = false
        if (res.code === 200) {
          let { data, total } = res.data
          this.tableData = data
          this.total = total
          if (key === 'list') {
     //        data.map(item => {
			  // this.order_price += parseFloat(item.pay_price, 2)
     //        })
          }
        }
      })
    },
    
	
	
	
	handleDelete (id) {
		let that = this
		that.$confirm(`你确认要删除ID为 ${id} 订单？`, that.$t('tips.reminder'), {
	    confirmButtonText: that.$t('action.comfirm'),
	    cancelButtonText: that.$t('action.cancel'),
	    type: 'warning'
	  }).then(() => {
	    that.onDelete(id)
	  }).catch(() => { })
	},
	
	async onDelete(id) {
		this.loading = true
		let { code } = await this.$api.shop.orderGoodDelete(id)
		this.loading = false
		if (code !== 200) return
		this.$message.success(this.$t('tips.successOper'))
		this.getTableDataList(1, 'list')
	},
    
	
	handleCancel (id) {
		let that = this
	  that.$confirm(`你确认要取消ID为 ${id} 订单？`, that.$t('tips.reminder'), {
	    confirmButtonText: that.$t('action.comfirm'),
	    cancelButtonText: that.$t('action.cancel'),
	    type: 'warning'
	  }).then(() => {
	    that.onCancel(id)
	  }).catch(() => { })
	},
	
	async onCancel(id) {
		this.loading = true
		let { code } = await this.$api.shop.orderGoodCancel(id)
		this.loading = false
		if (code !== 200) return
		this.$message.success(this.$t('tips.successOper'))
		this.getTableDataList(1, 'list')
	},
	
	
	handleSend (id,type) {
		let that = this
	  // that.$prompt(`请输入物流单号`, that.$t('tips.reminder'), {
	  //   confirmButtonText: that.$t('action.comfirm'),
	  //   cancelButtonText: that.$t('action.cancel'),
	  //   type: 'warning'
	  // }).then(() => {
	  //   that.onCancel(id)
	  // }).catch(() => { })
	  
	  if(type == 2) {
		  that.$confirm(`你确认要完成ID为 ${id} 订单？`, that.$t('tips.reminder'), {
		    confirmButtonText: that.$t('action.comfirm'),
		    cancelButtonText: that.$t('action.cancel'),
		    type: 'warning'
		  }).then(() => {
		    that.onSend(id)
		  }).catch(() => { })
		  return 
	  }
	  
	  
	  that.handleExpress(id, 'send')
	  
	 //  this.$prompt('请输入物流单号', that.$t('tips.reminder'), {
		// confirmButtonText: that.$t('action.comfirm'),
		// cancelButtonText: that.$t('action.cancel'),
		// inputPattern: /\S/,
		// inputErrorMessage: '请输入物流单号'
	 //  }).then(({ value }) => {
		// that.onSend(id, value)
	 //  }).catch(() => {
		  
	 //  });
	},
	
	async onSend(id, express_id="", company="", companyName="") {
		this.loading = true
		let { code } = await this.$api.shop.orderGoodSend({id: id, express_id: express_id, company: company, companyName: companyName})
		this.loading = false
		if (code !== 200) return
		this.$message.success(this.$t('tips.successOper'))
		
		this.expressPopup = false
		
		this.getTableDataList('', 'list')
	},
	
	
	expressPopupClose() {
		this.expressForm.express_id = null
		// this.expressForm.type = null
		this.expressForm.orderId = null
	},
	
	handleExpress(id, type, row=undefined) {
		this.expressForm.type = type
		this.expressForm.orderId = id
		
		// console.log(row)
		if(row) {
			this.expressForm.express_id = row.express_id
			this.expressForm.company = row.company
			this.expressForm.companyName = row.company_name
		}
		
		this.expressPopup = true
	},
	
	
	handleExpressSubmit() {
		this.$refs.expressForm.validate((valid) => {
			if (valid) {
				
				// 验证数据
				// console.log(this.expressForm);return
				if(this.expressForm.type == 'change') {
					this.onExpressSubmit()
				}
				if(this.expressForm.type == 'send') {
					this.onSend(this.expressForm.orderId, this.expressForm.express_id, this.expressForm.company, this.expressForm.companyName)
				}
			}
		});
	},
	
	// 修改物流单号
	async onExpressSubmit() {
		this.loading = true
		let { code } = await this.$api.shop.orderGoodExpressChange({
			id: this.expressForm.orderId,
			express_id: this.expressForm.express_id,
			company: this.expressForm.company,
			companyName: this.expressForm.companyName
		})
		this.loading = false
		if (code !== 200) return
		this.$message.success(this.$t('tips.successOper'))
		
		this.expressPopup = false
		
		this.getTableDataList('', 'list')
	},
	
	
	
    
    
    /**
     * @name: 导出数据
     */
    toExportExcel () {
      this.downloadLoading = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm))
      let { start_time: time } = searchForm
      if (time && time.length > 0) {
        searchForm.start_time = time[0] / 1000
        searchForm.end_time = time[1] / 1000
      } else {
        searchForm.start_time = ''
        searchForm.end_time = ''
      }
      let url = this.$util.getProCurrentHref()
      let keywords = url.indexOf('?') > 0 ? '' : '?'
      let flag = url.indexOf('?') > 0
      Object.getOwnPropertyNames(searchForm).forEach((keys, value) => {
        keywords += flag
          ? `&${keys}=${searchForm[keys]}`
          : `${keys}=${searchForm[keys]}`
        flag = true
      })
      let token = window.localStorage.getItem('massage_minitk')
      let dwonlaodUrl = `${url}/massage/admin/AdminExcel/orderList${keywords}&token=${token}`
      window.location.href = dwonlaodUrl
      setTimeout(() => {
        this.downloadLoading = false
      }, 5000)
    },
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-shop-order {
  .page-main {
    width: 100%;

    .el-select,
    .el-input-number,
    .el-input {
      width: 200px;
    }

    .bell-tag {
      top: 10px;
      left: 0;
      width: 50px;
      height: 20px;
      background: #f12c20;
      border-radius: 5px 0 10px 0;
      .text {
        scale: 0.8;
      }
    }

    .dialog-form {
      .el-select,
      .el-input-number,
      .el-input {
        width: 300px;
      }
    }
  }
}

.none {
  display: none;
}
</style>
<style media="print">
.none {
  display: block;
}
</style>
